import 'dart:async';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_diy_list_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/create_building_index_page.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/system_ui_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_dialog_widget/general_animation_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'building_index_detail_response_bean.dart';
import 'building_index_diy_detail_page.dart';
import 'building_index_page.dart';
import 'building_index_view_model.dart';
import 'create_floor_company_page.dart';
import 'edit_delete_pop_menu_widget.dart';
import 'new_create_floor_company_page.dart';

/// diy指示牌设置楼层页面
class BuildingIndexDiyFloorSettingsPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "BuildingIndexDiyFloorSettingsPage";
  //楼层水牌id
  final String buildingIndexId;
  final ComWbrandBean companyInfo;
  //来源 00我制作的详情，模板制作01
  final String from;
  const BuildingIndexDiyFloorSettingsPage(
      {Key key, this.buildingIndexId, this.companyInfo, this.from}) : super(key:key);

  @override
  _BuildingIndexDiyFloorSettingsPageState createState() => _BuildingIndexDiyFloorSettingsPageState();
  static Future<dynamic> navigatorPush(BuildContext context, String buildingIndexId,
      String from, {ComWbrandBean companyInfo}){
    return RouterUtils.routeForFutureResult(
        context,
        BuildingIndexDiyFloorSettingsPage(
          buildingIndexId: buildingIndexId,
          companyInfo: companyInfo,
          from: from,
        ),
        routeName: BuildingIndexDiyFloorSettingsPage.ROUTER
    );
  }
}

class _BuildingIndexDiyFloorSettingsPageState
    extends BaseState<BuildingIndexDiyFloorSettingsPage> {
  int _terminalCount = 0;
  BuildingIndexViewModel _viewModel;
  String _buildingIndexId;
  ComWbrandBean _detailInfo;
  List<FloorCompanyListBean> _upFloorList;
  List<FloorCompanyListBean> _downFloorList;
  StreamSubscription _diyUpdateStreamSubscription;
  List<String> _upFloorNumList;
  List<String> _downFloorNumList;
  @override
  void initState() {
    _upFloorList = new List();
    _downFloorList = new List();
    _upFloorNumList = new List();
    _downFloorNumList = new List();
    _buildingIndexId = widget?.buildingIndexId;
    _viewModel = BuildingIndexViewModel(this);
    _viewModel.getBuildingIndexDetail(_buildingIndexId);
    super.initState();
    _diyUpdateStreamSubscription =
        VgEventBus.global.on<RefreshDiyPageEvent>()?.listen((event) {
          _viewModel.getBuildingIndexDetail(_buildingIndexId);
        });

  }

  Future<bool> _withdrawFront() async{
    if("00" == widget?.from){
      //不需要跳转详情，直接返回
      return true;
    }
    //从模板制作来，需要跳转详情
    RouterUtils.popUntil(context, BuildingIndexPage.ROUTER);
    BuildingIndexDiyBean itemInfo = new BuildingIndexDiyBean();
    itemInfo.id = _detailInfo.id;
    itemInfo.htmlurl = _detailInfo.htmlurl;
    itemInfo.picurl = _detailInfo.picurl;
    itemInfo.picurl = _detailInfo.picurl;
    BuildingIndexDiyDetailPage.navigatorPush(context, itemInfo, true);
  }

  void onBackPressed(){
    if("00" == widget?.from){
      //不需要跳转详情，直接返回
      RouterUtils.pop(context);
      return;
    }
    //从模板制作来，需要跳转详情
    RouterUtils.popUntil(context, BuildingIndexPage.ROUTER);
    BuildingIndexDiyBean itemInfo = new BuildingIndexDiyBean();
    itemInfo.id = _detailInfo.id;
    itemInfo.htmlurl = _detailInfo.htmlurl;
    itemInfo.picurl = _detailInfo.picurl;
    itemInfo.picurl = _detailInfo.picurl;
    BuildingIndexDiyDetailPage.navigatorPush(context, itemInfo, true);
  }

  @override
  void dispose() {
    super.dispose();
    _diyUpdateStreamSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
      child: WillPopScope(
        onWillPop: _withdrawFront,
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: _toPlaceHolderWidget(),
        ),
      ),
    );
  }


  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getBuildingIndexDetail(_buildingIndexId),
            loadingOnClick: () => _viewModel
                .getBuildingIndexDetail(_buildingIndexId),
            child: child,
          );
        },
        child: _toInfoWidget());
  }

  Widget _toInfoWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.buildingIndexDetailValueNotifier,
      builder: (BuildContext context, BuildingIndexDetailBean detailBean, Widget child){
        if(detailBean != null && detailBean.comWbrand != null){
          _detailInfo = detailBean.comWbrand;
          _upFloorList.clear();
          _downFloorList.clear();
          _upFloorList.addAll(detailBean.upList);
          _downFloorList.addAll(detailBean.downList);
        }
        return _toMainColumnWidget();
      },
    );
  }


  Widget _toMainColumnWidget() {
    return Stack(
      children: [
        Column(
          children: [
            _toTopBarWidget(),
            _toBuildingIndexTitleWidget(),
            SizedBox(height: 10,),
            _floorListWidget(),
          ],
        ),
        _toBottomWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "楼层指示牌",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toTerminalWidget(),
      navFunction: onBackPressed,
    );
  }
  ///播放终端
  Widget _toTerminalWidget(){
    return Container();
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_terminalCount < 1){
          return;
        }

      },
      child: Container(
        height: 24,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
            color: (_terminalCount > 0)
                ? ThemeRepository.getInstance().getHintGreenColor_00C6C4()
                : ThemeRepository.getInstance().getMinorRedColor_F95355(),
            borderRadius: BorderRadius.circular(12)
        ),
        child: Text(
          "播放终端·${_terminalCount??0}",
          style: TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w600
          ),
        ),
      ),

    );
  }

  ///指示牌标题
  Widget _toBuildingIndexTitleWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        //01编辑
        CreateBuildingIndexPage.navigatorPush(context, "01", "",
            comWbrand: _detailInfo, upFloorNumList: _upFloorNumList,
            downFloorNumList: _downFloorNumList);
      },
      child: Container(
        height: 50,
        color: Colors.white,
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: Text(
                _detailInfo?.wtitle??"",
                style: TextStyle(
                  fontSize: 17,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  fontWeight: FontWeight.w600,
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
            SizedBox(width: 15,),
            Text(
              "共${getFloorCount()}层",
              style: TextStyle(
                fontSize: 13,
                color: Color(0xFF8B93A5),
              ),
            ),
            SizedBox(width: 9,),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }



  ///楼层列表-大
  Widget _floorListWidget() {
    _upFloorNumList.clear();
    _downFloorNumList.clear();
    return Expanded(
      child: Container(
        color: Colors.white,
        child: ListView.separated(
            itemCount: getFloorCount(),
            padding: EdgeInsets.only(bottom: getNavHeightDistance(context)+60, top: 0, left: 0, right: 0),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return _toFloorItemWidget(context, index);
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(
                height: 10,
                color: Color(0xFFF6F7F9),
              );
            }),
      ),
    );
  }

  ///楼层列表项-小
  Widget _toFloorItemWidget(BuildContext context, int index) {
    String floorName = getFloorName(index);
    List<FloorCompanyListBean> floorList = getFloorList(floorName);
    return Column(
      children: [
        _toFloorTitleWidget(index, floorName, floorList),
        ListView.separated(
            padding: EdgeInsets.all(0),
            itemCount: floorList?.length??0,
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return _toCompanyItemWidget(context, index, floorList[index], floorList);
            },
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 0,
              );
            })
      ],
    );
  }

  int getFloorCount(){
    if(_detailInfo == null){
      return 0;
    }
    int upStart = _detailInfo.usnum??0;
    int upEnd = _detailInfo.uenum??0;
    int upCount = 0;
    if(upStart != 0 && upEnd != 0 && upEnd >= upStart){
      upCount = upEnd - upStart + 1;
    }
    int downStart = _detailInfo.dsnum??0;
    int downEnd = _detailInfo.denum??0;
    int downCount = 0;
    if(downStart != 0 && downEnd != 0 && downEnd >= downStart){
      downCount = downEnd - downStart + 1;
    }
    return upCount + downCount;
  }

  ///获取楼层名
  String getFloorName(int index){
    int upStart = _detailInfo.usnum??0;
    int upEnd = _detailInfo.uenum??0;
    int downStart = _detailInfo.dsnum??0;
    int downEnd = _detailInfo.denum??0;
    int upCount = 0;
    int downCount = 0;
    if(upStart != 0 && upEnd != 0 && upEnd >= upStart){
      upCount = upEnd - upStart + 1;
    }
    if(downStart != 0 && downEnd != 0 && downEnd >= downStart){
      downCount = downEnd - downStart + 1;
    }
    int totalCount = upCount + downCount;
    if(index < upCount){
      //说明是楼上层
      return (upEnd - index).toString() + "F";
    }else{
      //说明是楼下层
      return "B" + (downStart + downCount - (totalCount -index)).toString();
    }
  }

  List<FloorCompanyListBean> getFloorList(String floorName){
    List<FloorCompanyListBean> floorList = new List();
    //得到当前item的楼层号
    String floor = floorName.replaceAll("F", "").replaceAll("B", "");

    if(floorName.contains("F")){
      //楼上层
      if(_upFloorList.isEmpty){
        return floorList;
      }else{
        //遍历楼上层，得到该楼层的企业列表
        _upFloorList.forEach((element) {
          if(floor == element.fnum){
            floorList.add(element);
            if(!_upFloorNumList.contains(element.fnum)){
              _upFloorNumList.add(element.fnum);
            }
          }
        });
      }
    }else{
      //楼下层
      if(_downFloorList.isEmpty){
        return floorList;
      }else{
        //遍历楼下层，得到该楼层的企业列表
        _downFloorList.forEach((element) {
          if(floor == element.fnum){
            floorList.add(element);
            if(!_downFloorNumList.contains(element.fnum)){
              _downFloorNumList.add(element.fnum);
            }
          }
        });
      }
    }
    return floorList;
  }

  ///楼层标题栏
  Widget _toFloorTitleWidget(int index, String floorName, List<FloorCompanyListBean> floorList){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        //创建还是编辑 00创建 01编辑
        // CreateFloorCompanyPage.navigatorPush(context, "00", floorName: floorName,
        //     buildingIndexId: _buildingIndexId, comWbrandBean: _detailInfo);
        List<FloorCompanyListBean> tempList = new List();
        tempList.addAll(floorList);
        bool result = await NewCreateFloorCompanyPage.navigatorPush(context, _buildingIndexId, floorName,
            null, tempList);
        if(!(result??false)){
          _viewModel.getBuildingIndexDetail(_buildingIndexId);
        }
      },
      child: Column(
        children: [
          Container(
            height: 40,
            padding: EdgeInsets.symmetric(horizontal: 15),
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                Text(
                  floorName,
                  style: TextStyle(
                      fontSize: 12,
                      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                      fontWeight: FontWeight.w600
                  ),
                ),
                Spacer(),
                Text(
                  "添加/修改",
                  style: TextStyle(
                    fontSize: 11,
                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 0.5,
            margin: EdgeInsets.symmetric(horizontal: 15),
            color: Color(0xFFEEEEEE),
          ),
        ],
      ),
    );
  }

  ///楼层公司列表item
  Widget _toCompanyItemWidget(BuildContext context, int index, FloorCompanyListBean companyItem, List<FloorCompanyListBean> floorList) {
    return Container(
      height: 40,
      padding: EdgeInsets.only(left: 15, right: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Expanded(
            child: Text(
              companyItem?.company??"暂无公司名",
              overflow: TextOverflow.ellipsis,
              maxLines: 2,
              style: TextStyle(
                fontSize: 14,
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              ),
            ),
          ),
          SizedBox(
            width: 10,
          ),
          Visibility(
            visible: StringUtils.isNotEmpty(companyItem?.hnum??""),
            child: Container(
              width: 100,
              alignment: Alignment.centerRight,
              child: Text(
                companyItem?.hnum??"暂无门牌号",
                style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          // GestureDetector(
          //   behavior: HitTestBehavior.opaque,
          //   onTapUp: (details) {
          //     _showEditMenuDialog(details, companyItem, floorList);
          //   },
          //   child: Container(
          //     margin: EdgeInsets.only(left: 5),
          //     width: 33,
          //     alignment: Alignment.center,
          //     child: Image.asset(
          //       "images/icon_edit_floor_company_info.png",
          //       width: 3,
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }

  void _showEditMenuDialog(TapUpDetails details, FloorCompanyListBean companyItem, List<FloorCompanyListBean> floorList) {
    showAnimationDialog(
        context: context,
        transitionType: TransitionType.fade,
        barrierColor: Color(0x00000001),
        transitionDuration: Duration(milliseconds: 100),
        builder: (context) {
          return EditDeletePopMenuWidget(
            items: ["编辑", "删除"],
            details: details,
            onClickItem: (content) async{
              RouterUtils.pop(context);
              if (content == "编辑") {
                //创建还是编辑 00创建 01编辑
                // CreateFloorCompanyPage.navigatorPush(context, "01", companyInfo: companyItem, comWbrandBean: _detailInfo);
                List<FloorCompanyListBean> tempList = new List();
                tempList.addAll(floorList);
                bool result = await NewCreateFloorCompanyPage.navigatorPush(context, _buildingIndexId, "",
                    companyItem, tempList);
                if(!(result??false)){
                  _viewModel.getBuildingIndexDetail(_buildingIndexId);
                }

              } else {
                bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: "确认删除当前企业？",
                  cancelText: "取消",
                  confirmText: "删除",
                  confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  cancelBgColor: Color(0xFFF6F7F9),
                  titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  widgetBgColor: Colors.white,
                );
                if (result ?? false) {
                  _viewModel.deleteFloorCompany(context, companyItem?.id);
                }
              }
            },
          );
        }
    );
  }

  ///底部查看效果
  Widget _toBottomWidget(){
    double bottomH = ScreenUtils.getBottomBarH(context);
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 60 + bottomH,
        color: Colors.white,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 15, right: 15, bottom: bottomH),
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            //来源 00我制作的详情，模板制作01
            if("00" == widget?.from){
              RouterUtils.pop(context);
            }else if("01" == widget?.from){
              RouterUtils.popUntil(context, BuildingIndexPage.ROUTER);
              BuildingIndexDiyBean itemInfo = new BuildingIndexDiyBean();
              itemInfo.id = _detailInfo.id;
              itemInfo.htmlurl = _detailInfo.htmlurl;
              itemInfo.picurl = _detailInfo.picurl;
              itemInfo.picurl = _detailInfo.picurl;
              BuildingIndexDiyDetailPage.navigatorPush(context, itemInfo, true);
            }else{
              RouterUtils.pop(context);
            }
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              height: 40,
              alignment: Alignment.center,
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              child: Text(
                "查看效果",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
